package com.ymcv.proyecto7.tools;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import com.ymcv.proyecto7.controller.UsuarioController;
import com.ymcv.proyecto7.model.entity.Usuario;

public class Location extends AsyncTask<Void, Void, String> {

	Context context;
	Usuario u;
	UsuarioController con;

	public Location(Context c) {
		context = c;
	}

	@Override
	protected String doInBackground(Void... arg0) {
		String msj = "";
		con = new UsuarioController(context);
		u = con.obtenerUsuario();
	
		try {
			//String url = "http://199.192.79.50/proyecto7/ws/";
			String url ="http://desarrollo.yoelcardenas.com/";
			HttpGet get = new HttpGet(
					 url+"cablocation.php?cabid=" + u.getId_unidad()
					 + "&cablat="+u.getLat()+"&cablon="+u.getLon());

			HttpClient cliente = new DefaultHttpClient();
			HttpResponse response = cliente.execute(get);
			InputStream is = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"), 8);
			StringBuilder sb = new StringBuilder();
			String linea = null;
			while ((linea = br.readLine()) != null) {
				sb.append(linea);
			}
			msj = sb.toString();
			is.close();
			br.close();
		} catch (Exception e) {

		}
		return msj;
	}

	
	
	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		String fec = sdf.format(Calendar.getInstance().getTime());
		try {
			JSONObject json = new JSONObject(result);
			if (json.getString("rcvd").equals("OK")) {
				u.setFecha_mod(fec);
				u.setIntentos(0);
				con.actualizarIntentos(u);
			}else{
				u.setIntentos(u.getIntentos()+1);
				con.actualizarIntentos(u);
			}
			
		} catch (Exception e) {
			u.setIntentos(u.getIntentos()+1);
			con.actualizarIntentos(u);
		}
		Intent intent = new Intent("location");
		Bundle b = new Bundle();
		b.putInt("intentos", u.getIntentos());
		b.putString("fecha", fec);
		intent.putExtras(b);
		context.sendBroadcast(intent);
	}

}
